// productDetail.js
const regeneratorRuntime = require('../../lib/runtime');
const wx = require('../../lib/wx');
const Api = require('../../utils/api.js');
const wxapp = require('../../lib/wxapp');
const Util = require('../../utils/util.js');
const WxParse = require('../../wxParse/wxParse.js');

// 获取应用实例
const app = getApp();
Page({
  data: {
    indicatorDots: true,
    goods_id:0,
    goods_price:[],
    autoplay: false,
    interval: 5000,
    duration: 500,
    circular: false,
    currentExpress: '物流说明',
    currentPrice: 0,
    productDetail: {
      imgUrl: [
        '',
      ],
      people: 2,
      title: '品牌',
      subTitle: '标题',
      currentPrice: '00.00',
      orignPrice: '00.00',
      groupPrice: '00.00',
      discount: '00',
      stock: 100,
      countdownSeconds: 12800,
      countdownHour: 0,
      countdownMin: 0,
      countdownSec: 0,
      type: 0
    },
    brandDetail: {
      logo: '',
      name: '',
      list:[
        {
          imgUrl: '../images/no_image.png',
          url: '../productDetail/productDetail',
          price: '189.00',
          discount: '40',
        },
      ],
    },
    productList: [
      {
        imgUrl: '',
        url: '../productDetail/productDetail',
        title: '标题',
        price: '00.00',
        discount: '100',
        shop: '品牌',
      },

    ],
    actionActive: false,
    animationData: {},
    windowHeight: 0,
    area: ['美国', '中国', '巴西', '日本'],
    areaIndex: 0,
    productSpecification: [
      {
        type: '颜色',
        name: 'color',
        selectItem: '',
        value: ['白色', '黑色', '红色'],
      },
      {
        type: '尺码',
        name: 'size',
        selectItem: '',
        value: ['42', '42.5', '43', '44', '45'],
      },
    ],
    addDis: false,
    cutDis: true,
    productNum: 1,
  },

  backToHome: wxapp.handler(function* backToHome(next) {
    wx.reLaunch({
      url: '../index/index',
    });

    yield next;
  }),

  goToShoppingCart: wxapp.handler(function* goToShoppingCart(next, e) {
    const url = '../shoppingCart/shoppingCart';
    wx.reLaunch({
      url,
    });

    yield next;
  }),

  goToBrandList: wxapp.handler(function* goToBrandList(next) {
    wx.navigateTo({
      url: '../brandDetail/brandDetail',
    });

    yield next;
  }),

  goToDetail: wxapp.handler(function* goToDetail(next, e){
    const url = e.currentTarget.dataset.url;
    wx.navigateTo({
      url: url,
    });

    yield next;
  }),

  switchExpress: wxapp.handler(function* switchExpress(next, e){
    const currentExpress = e.currentTarget.dataset.express;
    this.setData({
      currentExpress,
    });

    yield next;
  }),

  orderSubmit: wxapp.handler(function* orderSubmit(next, e){
    const authTokenKey = Util.authTokenKey();
    const token = wx.getStorageSync(authTokenKey);
    const url = '../login/login';
    if(!token){
      wx.reLaunch({
        url,
      });
      return;
    }
    var select_item = false;
    for (var i = 0; i < this.data.productSpecification.length;i++){
      console.log(this.data.productSpecification[i]);
      console.log(this.data.productSpecification[i].selectItem);
      if (this.data.productSpecification[i].selectItem){
        select_item = true;
        break;
      }
    }
    
    if (!select_item && this.data.productSpecification.length>0){
      wx.showToast({
        title: '请选择商品规格',
        image: '../../images/error.png',
        duration: 2000,
      });
      return;
    }

    const submitValue = e.detail.value;
    const productNum = submitValue.productNum;
    const price = submitValue.price;
    const submitType = e.detail.target.id;
    const goods_id = this.data.goods_id;

    if(submitType === 'cart'){
      wx.showToast({
        title: '成功加入购物车',
        icon: 'success',
        duration: 2000,
      });
      // 加入购物车
      var carKey = Util.carKey();
      var carData = wx.getStorageSync(carKey);
      if(carData){
        carData.push(e.detail.value);
      }else{
        carData = [];
        carData.push(e.detail.value);
      }
      wx.setStorageSync(carKey, carData);

      var that = this;
      var getAddGoodsCar = Api.getAddGoodsCar();
      let postData = JSON.stringify(e.detail.value);
      // 购物车
      wx.request({
        url: getAddGoodsCar,
        header: {
          'content-type': 'application/x-www-form-urlencoded'
        },
        method: 'POST',
        data: {//发送给后台的数据
          info: postData,
          token:token
        },
        complete: function (res) {

        }
      });




      const url = '../shoppingCart/shoppingCart';
      wx.navigateTo({
        url,
      });
    } else if(submitType === 'purchase'){
      //wx.showToast({
      //  title: '正在生成订单',
      //  icon: 'loading',
      //  duration: 2000,
      //});
      var goods = [];
      goods.push(submitValue);
      const url = `../orderConfirm/orderConfirm?buyType=2&attr=${submitValue.order_attr}&goodsInfo=${JSON.stringify(goods)}`;
      wx.navigateTo({
        url,
      });
    }
  }),

  // 预览图片
  previewImage: wxapp.handler(function* previewImage(next) {
    const urls = this.data.productDetail.imgUrl;

    yield wx.previewImage({
      urls,
    });

    yield next;
  }),

  // 显示购买弹窗
  showOfferAction: wxapp.handler(function* showOfferAction(next, e) {
    const pageData = this.data;
    const windowHeight = -pageData.windowHeight + 'px';
    const isGroup = e.currentTarget.dataset.group;
    let goGroup;
    if(isGroup){
      goGroup = true;
    } else{
      goGroup = false;
    }
    this.setData({
      goGroup,
    });
    const animation = wx.createAnimation({
      duration: 200,
    });
    this.animation = animation;

    if (pageData.actionActive === true) {
      animation.bottom(windowHeight).step();
      this.setData({
        actionActive: false,
      });
    } else {
      animation.bottom('0').step();
      this.setData({
        actionActive: true,
      });
    }

    this.setData({
      animationData: animation.export(),
    });

    yield next;
  }),

  closeAction: function closeAction() {
    const windowHeight = -this.data.windowHeight + 'px';
    this.animation.bottom(windowHeight).step();

    this.setData({
      animationData: this.animation.export(),
      actionActive: false,
    });
  },

  hideAction: wxapp.handler(function* hideAction(next) {
    this.closeAction();

    yield next;
  }),

  bindPickerChange: wxapp.handler(function* bindPickerChange(next, e) {
    this.setData({
      areaIndex: e.detail.value
    });

    yield next;
  }),

  selectItem: wxapp.handler(function* selectItem(next, e){
    const currentValue = e.target.dataset.value;
    const currentIndex = e.target.dataset.index;
    const item_id = e.target.dataset.item_id;
    const goods_price =  this.data.goods_price;
    var goods_id = this.data.goods_id;
    var keyStr = '';
    for(var i = 0;i < goods_price.length; i++) {
      keyStr += '-'+goods_price[i]['key'];
    }
    var regex = new RegExp(item_id, 'g'); // 使用g表示整个字符串都要匹配
    var result = keyStr.match(regex);
    var count = !result ? 0 : result.length;
    if(count == 1){
      var price = 0 ;
      for(var i = 0;i < goods_price.length; i++) {
        var regex = new RegExp(item_id, 'g'); // 使用g表示整个字符串都要匹配
        var result = goods_price[i]['key'].match(regex);
        var count = !result ? 0 : result.length;
        if(count){
          price = goods_price[i]['price'];
          goods_id = goods_price[i]['goods_id'];
          break;
        }
      }
      this.setData({ currentPrice: price,goods_id:goods_id});
    }
    const pageData = this.data;
    let productSpecification = pageData.productSpecification;
    if(productSpecification[currentIndex].selectItem === currentValue){
      productSpecification[currentIndex].selectItem = '';
    } else{
      productSpecification[currentIndex].selectItem = currentValue;
    }
    this.setData({
      productSpecification,
    });

    yield next;
  }),

  inputQty: wxapp.handler(function* inputQty(next, e) {
    let productNum = parseInt(e.detail.value);
    const pageData = this.data;
    const stock = pageData.productDetail.stock;
    let cutDis;
    if(productNum > 1) {
      cutDis = false;
    } else {
      cutDis = true;
    }
    let addDis = false;
    if(stock > 0 && productNum > stock){
      addDis = true;
      productNum = stock;
    }

    this.setData({
      addDis,
      cutDis,
      productNum,
    });

    yield next;
  }),

  cutNum: wxapp.handler(function* cutNum(next, e) {
    const pageData = this.data;
    let productNum = pageData.productNum;
    let cutDis = pageData.cutDis;
    if (cutDis) {
      return;
    }

    productNum -= 1;
    if(productNum === 1) {
      cutDis = true;
    }

    const stock = pageData.productDetail.amount;
    let addDis = false;
    if(stock > 0 && productNum === stock){
      addDis = true;
    }

    this.setData({
      addDis,
      cutDis,
      productNum,
    });

    yield next;
  }),

  addNum: wxapp.handler(function* cutNum(next, e) {
    const pageData = this.data;
    let productNum = pageData.productNum || 0;
    const stock = pageData.productDetail.stock;
    let cutDis = true;
    let addDis = false;
    if(stock > 0 && productNum === stock){
      return;
    }
    productNum += 1;
    if(stock > 0 && productNum === stock){
      addDis = true;
    }
    if(productNum > 1) {
      cutDis = false;
    }
    this.setData({
      addDis,
      cutDis,
      productNum,
    });

    yield next;
  }),

  onTimer: function onTimer() {
    let productDetail = this.data.productDetail;
    let countdown = productDetail.countdownSeconds;
    if (!countdown || isNaN(countdown)) {
      const isGroup = false;
      this.setData({
        isGroup,
      })
      return;
    }

    countdown -= 1;
    if (countdown >= 0) {
      productDetail.countdownSeconds = countdown;
      let base = parseInt(countdown/3600);
      let hour = parseInt(base);
      let minute = parseInt((countdown-3600*base)/60);
      let second = parseInt(countdown-3600*base-60*minute);
      if(hour < 10){
        hour = '0' + hour;
      }
      if(minute < 10){
        minute = '0' + minute;
      }
      if(second < 10){
        second = '0' + second;
      }
      productDetail.countdownHour = hour;
      productDetail.countdownMin = minute;
      productDetail.countdownSec = second;
      this.setData({
        productDetail,
      });
      const timer = setTimeout(() => {
        this.onTimer();
      }, 1000);
    } else {
      const isGroup = false;
      this.setData({
        isGroup,
      });
    }
  },

  onShow: wxapp.handler(function* onShow(next) {
    if(this.data.productDetail.countdownSeconds !== '') {
      this.onTimer();
    }

    yield next;
  }),

  onLoad: wxapp.handler(function* onLoad(next, options) {
    var that = this;
    const isGroup = options.isGroup;

    that.setData({
      isGroup,
    });

    const systemInfo = wx.getSystemInfoSync();
    const windowHeight = systemInfo.windowHeight;

    const goods_id = options.goods_id;

    that.setData({
      windowHeight,
      goods_id:goods_id
    });

    var getGoodsDetail = Api.getGoodsDetail();
    var getRelatedGoods = Api.getRelatedGoods();

    // 商品详情
    wx.request({
      url: getGoodsDetail,
      header: {
        'content-type': 'application/json'
      },
      method: 'GET',
      data: {//发送给后台的数据
        goods_id: goods_id
      },
      complete: function (res) {
        that.setData({ 
          productDetail: res.data.data ,          productSpecification:res.data.spec ,
          article: WxParse.wxParse('article', 'html', res.data.data.goods_content, that, 5),
          goods_price: res.data.goods_price,
          currentPrice:res.data.data.currentPrice
          });
      }
    });
    // console.log(this.data.goods_price);
    // 相关单品
    wx.request({
      url: getRelatedGoods,
      header: {
        'content-type': 'application/json'
      },
      method: 'GET',
      data: {//发送给后台的数据
        goods_id: goods_id
      },
      complete: function (res) {
          that.setData({ productList: res.data.data});
        }
      });

      yield next;

  }),

  onShareAppMessage: function () {
    return {
      title: this.data.productDetail.title,
      path: '/pages/productDetail/productDetail?goods_id=' + this.data.goods_id
    }
  }

});
